#include "logger.hpp"
#include <sys/socket.h>
#include <arpa/inet.h>
#include "thread.hpp"
using namespace thread_module;
using namespace logger_module;
std::string server_ip;
uint16_t server_port;
int sockfd = 0;
struct sockaddr_in server;
pthread_t send_tid;
pthread_t recv_tid;
void Send()
{
    while(true)
    {
        std::string input;
        std::cout<<"Please enter# ";
        std::getline(std::cin,input);
        sendto(sockfd,input.c_str(),input.length(),0,(struct sockaddr*)&server,sizeof(server));
        if(input=="QUIT")
        {
        sleep(1);
        pthread_cancel(recv_tid);
        break;
        }
    }
}
void Recv()
{
    while (true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
        if(m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer << std::endl;

            if(buffer=="QUIT")
            {
                sleep(1);
                break;
            }
        }
        else
        {
            LOG(log_level::ERROR)<<"receive nothing";
        }
    }
}
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        std::cerr<<"please enter#ip port"<<std::endl;
        exit(1);
    }
    server_ip =argv[1];
    server_port =std::stoi(argv[2]);
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if (sockfd < 0)
    {
        LOG(log_level::FATAL) << "sockfd get failure";
        exit(1);
    }
    server.sin_family = AF_INET;
    server.sin_port=htons(server_port);
    server.sin_addr.s_addr=inet_addr(server_ip.c_str());
    //不用bind的原因是 不需要 因为OS知道ip地址 端口号随便给一个就行
    //因为客户端不用服务器主动去找,都是客户端找服务器,服务器就知道端口号了
   
    thread sender(Send);
    thread recver(Recv);
    sender.start();
    recver.start();
    send_tid=sender.get_tid();
    recv_tid=recver.get_tid();
    sender.join();
    recver.join();
    return 0;

}